#include <stdlib.h>
#include <malloc.h>
#include "sleep.h"
#include "process.h"

PCB newPCB(const int process_id) {
	PCB pcb = (PCB) malloc(sizeof(PCBStr));
	pcb->process_id = process_id;
	pcb->next_step = 0;
	pcb->state = 1;
	pcb->waiting_on = 0;
	pcb->owns = 0;
	return pcb;
}

void setPcbBlocked(PCB pcb, const int waiting_on) {
	pcb->state = 3;
	pcb->waiting_on = waiting_on;
}

void setPcbReady(PCB pcb) {
	pcb->state = 1;
	pcb->waiting_on = 0;
}

Process newProcess(const int id,
		           const int num_instructions,
                   const int num_requests,
                   enum ProcessType process_type) {

	Process process = (Process) malloc(sizeof(ProcessStr));
    if (process) {
    	process->pcb = newPCB(id);
        process->num_instructions = num_instructions;
        process->num_requests = num_requests;
        process->process_type = process_type;
    }
    return process;
}

int processInstruction(const Process process,
		        		int instruction) {
	int rv = -1;
	int time = WORK_UNIT;
	int some_magic_number = process->num_instructions / process->num_requests;

	if (instruction % some_magic_number == 0) {
		rv = process->process_type;
	} else {
		milliSleep(time);
	}
	//this only processes 1 instruction.
	return rv;
}

